package com.example.stray_animal_management_system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.stray_animal_management_system.entity.MessageBoard;
import com.example.stray_animal_management_system.entity.User;
import com.example.stray_animal_management_system.service.MessageBoardService;
import com.example.stray_animal_management_system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: panpan
 * @time: 2025/11/2
 */
@RestController
@RequestMapping("/api/message")
public class MessageBoardController {

    @Autowired
    private MessageBoardService messageService;

    @Autowired
    private UserService userService;

    /**
     * 用户发布留言
     */
    @PostMapping("/add")
    public Map<String, Object> add(@RequestBody MessageBoard msg) {
        Map<String, Object> res = new HashMap<>();

        msg.setCreateTime(LocalDateTime.now());
        messageService.save(msg);

        res.put("code", 200);
        res.put("msg", "留言发布成功");
        return res;
    }

    /**
     * 用户端 - 获取所有留言（包含他人留言）
     */
    @GetMapping("/list")
    public Map<String, Object> list() {
        List<MessageBoard> list = messageService.list(
                new QueryWrapper<MessageBoard>().orderByDesc("create_time")
        );

        Map<String, Object> res = new HashMap<>();
        res.put("code", 200);
        res.put("data", list);
        return res;
    }

    /**
     * 用户端 - 获取“我的留言”
     */
    @GetMapping("/my")
    public Map<String, Object> myList(@RequestParam("userId") Integer userId) {
        List<MessageBoard> list = messageService.lambdaQuery()
                .eq(MessageBoard::getUserId, userId)
                .orderByDesc(MessageBoard::getCreateTime)
                .list();

        Map<String, Object> res = new HashMap<>();
        res.put("code", 200);
        res.put("data", list);
        return res;
    }

    // ---------------------- 管理端 ----------------------

    /**
     * 管理端 - 查询留言（支持模糊搜索）
     */
    @GetMapping("/admin/list")
    public Map<String, Object> adminList(
            @RequestParam(value = "keyword", required = false) String keyword) {

        LambdaQueryWrapper<MessageBoard> query = new LambdaQueryWrapper<>();
        if (keyword != null && !keyword.isEmpty()) {
            query.like(MessageBoard::getContent, keyword)
                    .or().like(MessageBoard::getReply, keyword);
        }
        query.orderByDesc(MessageBoard::getCreateTime);

        List<MessageBoard> list = messageService.list(query);
        for (MessageBoard m : list) {
            User u = userService.getById(m.getUserId());
            if (u != null) m.setUsername(u.getNickname() != null ? u.getNickname() : u.getUsername());
        }

        Map<String, Object> res = new HashMap<>();
        res.put("code", 200);
        res.put("data", list);
        return res;
    }

    /**
     * 管理端 - 回复留言
     */
    @PutMapping("/admin/reply")
    public Map<String, Object> reply(@RequestParam("id") Integer id,
                                     @RequestParam("reply") String reply) {
        Map<String, Object> res = new HashMap<>();

        MessageBoard msg = messageService.getById(id);
        if (msg == null) {
            res.put("code", 404);
            res.put("msg", "留言不存在");
            return res;
        }

        msg.setReply(reply);
        messageService.updateById(msg);

        res.put("code", 200);
        res.put("msg", "回复成功");
        return res;
    }


    /**
     * 管理端 - 删除留言
     */
    @DeleteMapping("/admin/delete")
    public Map<String, Object> delete(@RequestParam("id") Integer id) {
        Map<String, Object> res = new HashMap<>();
        messageService.removeById(id);
        res.put("code", 200);
        res.put("msg", "删除成功");
        return res;
    }

}
